import React from 'react';
import { observer, inject} from 'mobx-react';
import { ListPage,BrowserHrm, } from 'weaver-mobile-page';
import { SearchBar, Button, Tools, Modal } from 'weaver-mobile';
import { withRouter, } from 'react-router-dom';
import NoData from '../../public/NoData.js';
const Normal = ListPage.Normal; 
const getLabel = Tools.getLabel;
const alert = Modal.alert;
const mobileshowtemplate = {
  tp_0: {
    theme: 'avatar',
    dataKeys: ['name', 'url', 'name', 'sub', 'jobTitle', 'dep'],
  },
};

@withRouter
@inject('calendarStore')
@observer
export default class HrmWorkplan extends React.Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentWillMount() {
    const { pathname } = this.props.location;
    const { setState } = this.props.calendarStore;
    setState({browser: new BrowserHrm.Store({route: pathname})})
  }

  componentDidMount() {
    const { getAttentionData, getUnderlining, currentUserID, mysubVisible} = this.props.calendarStore;
    const type = this.props.type;
    if(type=='mySub'){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(386548, '下属日程') })
    }else if(type=="myFllow"){
      window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(26469, '我的关注') })
    }
    localStorage.setItem('routeType',type); // 记录路由类型
    type === 'myFllow' && getAttentionData({searchStr:'',pageNum: '1'});
    if(type === 'mySub') {
      !mysubVisible && getUnderlining({userid: currentUserID,isAll: 0});
      mysubVisible && getUnderlining({userid: currentUserID,isAll: 1});
    }
  }

  componentWillUnmount() {
    const { setState1 } = this.props.calendarStore;
    setState1({ searchStr: '' });
    // localStorage.removeItem('routeType');
    // localStorage.removeItem('userName');
  }
  componentWillReceiveProps(nextProps){
    let prePathName = this.props.location.pathname
    let curPathName = nextProps.location.pathname
    if(curPathName&&curPathName!==prePathName){
      if(curPathName=="/calendar/subordinate"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(386548, '下属日程') })
      }else if(curPathName=="/calendar/myFllow"){
        window.em && window.em.checkJsApi('changeTitle') && window.em.changeTitle({ title: getLabel(26469, '我的关注') })
      }
    }
  }

  getSearch = (data) => {
    const { type } = this.props;
    const { getAttentionData, getUnderlining, mysubVisible, setState1 } = this.props.calendarStore;
    let name = data.replace(/\s/g,'');// 去除空格
    let isall = !mysubVisible ? 0: 1;
    setState1({ searchStr: name });
    type === 'myFllow' && getAttentionData({searchStr: name,isAll: isall, pageNum: 1}, 'searchMyFllow'); 
    type === 'mySub' && getUnderlining({searchStr: name,isAll: isall});
  }

  getPersonList = () => {
    const { type } = this.props;
    const { listUnderling, listAttention} = this.props.calendarStore;
    if(type === 'myFllow') return listAttention;
    if(type === 'mySub') return listUnderling;
  }

  getHeight = () => {
    const { pathname } = this.props.location;
    let H = document.getElementById('main-container').offsetHeight;
    H = window.innerHeight;
    if (pathname && pathname.indexOf('/workPlanViewList') > -1) {
      return H - window.getThemeVars()['search-bar-height']-2*window.getThemeVars()['hd']; //tab：45，search:44
    }
    return H - window.getThemeVars()['tabs-height'] - window.getThemeVars()['search-bar-height']-2*window.getThemeVars()['hd']; //tab：45，search:44
  }

  addMyFollow = (params) => {
    const { addAttention,setState, searchStr } = this.props.calendarStore;
    setState({btnAddDisabled: true});
    addAttention({touserid: params[0]}, () => this.getSearch(searchStr));
  }

  deleteMyFollow = (params) => {
    const {deleteMyFollow, searchStr} = this.props.calendarStore;
    alert('', getLabel(15097,'确定要删除吗？'), [
      { text: getLabel(386789,'取消'), onPress: () => {}, style: 'default' },
      { text: getLabel(386788,'确定'), onPress: () =>  deleteMyFollow({touserid: params.id}, () => this.getSearch(searchStr))},
    ]);
  }

  onRowClick = (arg) => {
    const { changeUserInfo} = this.props.calendarStore;
   
    this.props.history.push(`${window.location.hash.split('#')[1]}/schdule`)
    changeUserInfo(arg[0].id, arg[0].name)
    localStorage.setItem('userName',arg[0].name)
    localStorage.setItem('userId',arg[0].id)
    localStorage.setItem('hrmRoute','schdule')
  }

  onscroll = (e) => {
    const { totalpageNum, pageNum, getAttentionData, searchStr } = this.props.calendarStore;
    const type = this.props.type;
    if(e.target) {
      if(pageNum <= totalpageNum && e.target.scrollTop+e.target.offsetHeight === e.target.scrollHeight) {
        type === 'myFllow' && getAttentionData({searchStr:searchStr, pageNum: pageNum});
      }
    }
  }

  render() { 
    const { browser,btnAddDisabled } = this.props.calendarStore;
    const { type } = this.props;
    const { pathname } = this.props.location;
    let touchStyle = pathname.indexOf('/report/workPlanViewList') > -1 ? {} : {  };
    return (
      <div style={{overflow: 'hidden'}}>
        <div className="getSearchBar" >
          <SearchBar
            placeholder={getLabel(387355,'搜索')}
            onSubmit={(data) => {this.getSearch(data)}}
          />
        </div>
        <div  onScroll={this.onscroll}>
          {type==='myFllow' ? <div style={{ ...touchStyle, height: this.getHeight(),overflow:'auto',backgroundColor:'#f3f7fe' }}>
              {(this.getPersonList() && this.getPersonList().data.length>0) ? 
                <Normal 
                  template={mobileshowtemplate}
                  store={this.getPersonList()}
                  withSwipeAction={true}
                  swipeActionProps={    
                    {right:[
                      {
                        text: getLabel(386789,'取消'),
                        onPress: () => {},
                        style: { backgroundColor: '#ddd', color: 'white' },
                      },
                      {
                        text: getLabel(387789,'删除'),
                        onPress: (e) => this.deleteMyFollow(e),
                        style: { backgroundColor: '#F4333C', color: 'white' },
                      },
                    ]}
                  }     
                  onRowClick={(...arg) => {
                    const { pathname } = this.props.location;
                    if (pathname.indexOf('workPlanViewList') > -1) {
                      // 此处是为了限制日程一览表添加关注页面禁止点击人员
                    } else {
                      this.onRowClick(arg)
                    }
                  }}
                /> 
                : 
                <NoData message={getLabel(83553,'暂无数据')}/>
              }
              <div className="hrmworkplan-guanzhu" style={{ zIndex: 998 }}>
                <BrowserHrm
                  store={browser}
                  type={'17'}
                  onChange={(...arg) => {this.addMyFollow(arg)}}
                  viewAttr={btnAddDisabled ? 1 : 2}
                  >
                  <Button type="primary" disabled={btnAddDisabled} onClick={() => {}} >
                    {getLabel(26939,'添加关注')}
                  </Button>
                </BrowserHrm>
              </div>
          </div>
          :
          <div style={{ ...touchStyle, height: this.getHeight() + 47,overflow:'auto' }}>
            {(this.getPersonList() && this.getPersonList().data.length>0) ? 
              <Normal 
                template={mobileshowtemplate}
                store={this.getPersonList()}
                onRowClick={(...arg) => {
                  this.onRowClick(arg)
                }}
              />
              : 
              <NoData message={getLabel(83553,'暂无数据')} />
            }
          </div>
          }
        </div>
      
      </div>);
  }
}